#include "PatchStomper/StomperModel.h"
#include "PatchStomper/ToolElements/PatchInfoElement.h"
#include "StompedReality/Core/FileSystem.h"
#include "StompedReality/Math/Rectangle.h"
#include "StompedReality/Math/Vector2.h"
#include "StomperLib/Objects/RectPatchObject.h"
#include "StomperLib/RenderHelper.h"
#include <gl/GL.h>

namespace PatchStomper
{
PatchInfoElement::PatchInfoElement( StomperLib::BaseLayout* layout, StompedReality::IGame* game,
                                    StomperLib::EditorCamera* camera )
  : StomperLib::Elements::ObjectBaseTool( layout, game, camera )
{
  this->SelectionFunction = [&]( StomperLib::EditorObjectInfo* object )->bool
  {
    auto patchObj = (StomperLib::RectPatchObject*) object;
    return StompedReality::Math::Rectangle::Contains( patchObj->Pos, patchObj->Size, this->GetMousePos( ));
  };

}

PatchInfoElement::~PatchInfoElement( )
{
}

bool PatchInfoElement::Update( )
{
  return StomperLib::Elements::ObjectBaseTool::Update( );

}

void PatchInfoElement::RenderSelectedObjects( )
{
  if (!Model->ObjectList->IsObjectSelected( ))
    return;

  auto patchObject = Model->ObjectList->GetSelectedObject<StomperLib::RectPatchObject>( );

  glColor3f ( 0, 0, 1 );

  StomperLib::RenderHelper::DrawRect( patchObject->Pos, patchObject->Pos + patchObject->Size );

  glColor3f ( 1, 1, 1 );
}

void PatchInfoElement::RenderObjects( )
{
  glColor3f ( 1, 0, 0 );

  for (auto iter = Model->ObjectList->Begin( );
       iter != Model->ObjectList->End( );
       ++iter)
  {
    auto patchObject = (StomperLib::RectPatchObject*) *iter;
    StomperLib::RenderHelper::DrawRect( patchObject->Pos, patchObject->Pos + patchObject->Size );
  }

  glColor3f ( 1, 1, 1 );
}

void PatchInfoElement::OnSelectFile( Gwen::Event::Info info )
{
  this->SaveCurrentPatcheFile( );
  this->Model->ObjectList->Clear( );
  this->Model->CurrentWorkingFile = info.String.Get( );

  Gwen::String patchFile = this->Model->GetBaseFileName( this->Model->CurrentWorkingFile );
  patchFile.append( ".patches" );

  auto patchJson =  this->m_Game->getFileSystem( )->openAsJson( patchFile );
  ((PatchStomper::StomperModel*)this->Model)->NextSuffix = patchJson->get( "Next Suffix", 0 ).asUInt( );

  this->Model->ObjectList->Clear( );
  this->Model->ObjectList->ParseJson( patchJson->get( "Patches", 0 ) );
}

void PatchInfoElement::SaveCurrentPatcheFile( )
{
  if (this->Model->CurrentWorkingFile.empty( ))
    return;
  if (this->Model->Modified)
  {
    Gwen::String patchFile = this->Model->GetBaseFileName( this->Model->CurrentWorkingFile );
    patchFile.append( ".patches" );

    Json::Value patchJson;
    patchJson["Patches"] = this->Model->ObjectList->CreateJson( );
    patchJson["Next Suffix"] = ((PatchStomper::StomperModel*)this->Model)->NextSuffix;
    this->m_Game->getFileSystem( )->saveJson( patchJson, patchFile );
    this->Model->NotifySaved( this->Model->CurrentWorkingFile );
  }
}

}